package cn.bby.tools.actions;

import cn.bby.tools.dialog.TemplateGenInputDialog;
import cn.bby.tools.service.StateManagementService;
import cn.bby.tools.utils.AnActionEventUtils;
import cn.bby.tools.utils.TemplateGenHelper;
import cn.hutool.core.util.StrUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageDialogBuilder;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Set;

/**
 * @description: TestAction
 * @author: wby
 * @date: 2025/9/18 14:08
 * @version: 1.0
 */
public class GenTemplateAction extends AnAction {
    private final GenTemplateState state = StateManagementService.getInstanceState().genTemplateState;

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) return;
        String selectedText = AnActionEventUtils.getSelectedText(e);
        if (StrUtil.length(selectedText) < 20) {
            state.templateName = selectedText;
        }
        if (StrUtil.isEmpty(state.projectDir)) {
            state.projectDir = project.getBasePath();
        }
        // 创建并显示自定义对话框
        TemplateGenInputDialog dialog = new TemplateGenInputDialog(project, state);
        if (dialog.showAndGet()) {
            // 用户点击了确定按钮
            GenTemplateState data = dialog.getInputData();
            List<TemplateGenHelper.GenFileEnum> fileEnums = data.files.stream()
                    .map(TemplateGenHelper.GenFileEnum.nameMap::get)
                    .toList();
            try {
                String res = TemplateGenHelper.doGen(data.projectDir, data.savePkg, data.templateName, fileEnums,
                        data.userName, data.overWrite, data.note);
                MessageDialogBuilder.yesNo("创建完成", res)
                        .ask(project);
            } catch (Exception ex){
                MessageDialogBuilder.yesNo("出现错误", ex.toString())
                        .ask(project);
            }
        }
    }

    public static final List<String> allFiles = List.of(
            "Context",
            "ProcessTemplate",
            "PreValidate",
            "DoValidate",
            "PreProcess",
            "DoProcess",
            "PostProcess"
    );

    // 输入数据容器类
    public static class GenTemplateState {
        public String projectDir;
        public String savePkg;
        public String templateName;
        public Set<String> files;
        public String userName;
        public boolean overWrite;
        public String note;
    }

}
